<template>
    <div class="course" v-cloak>
        <div class="banner">
            <div class="course-name">{{courseInfo.name}}</div>
            <div class="course-desc">{{courseInfo.introduction}}</div>
        </div>
        <div class="schoolmate">
            <div class="mt-cols">
                <div class="mt-col-1">
                    <span class="count">{{totalStudentsCount}}</span>位宝宝一起学习
                </div>
                <div class="list">
                    <img v-for="(st,idx) in schoolmate" :key="idx" :src="st" :style="{'z-index': idx, 'right': (idx*.22+'rem')}">
                </div>
                <div class="more">
                    ...
                </div>
            </div>

        </div>
        <div class="course-wrap">
            <div class="course-nav">
                <!-- <mt-button size="small" @click.native.prevent="active = 'tab-container1'">tab 1</mt-button> -->
                <div class="mt-cols">
                    <div class="mt-col-2" v-for="(item, idx) of lessonList" :key="item.date" :class="{'active': active.split('-')[2] == item.date}" @click="active = 'tab-container-'+item.date">
                        <div class="day">{{item.day}}</div>
                        <div class="date" :class="{'primary': item.before}">{{item.date}}</div>
                        <div v-if="idx!=0 || manager" class="line" :class="{'primary': item.before}"></div>
                    </div>
                    <div v-if="manager" class="mt-col-2 picker-col">
                        <img src="./img/icon-picker.png" @click="openPicker">
                    </div>
                    <div v-else class="mt-col-1">

                    </div>
                </div>
            </div>
            <div class="page-tab-container">
                <mt-tab-container class="page-tabbar-tab-container" v-model="active" swipeable>
                    <mt-tab-container-item v-for="item in lessonList" :key="item.date" :id="'tab-container-' + item.date">
                        <div class="course-item-wrap">
                            <template v-if="item.list.length > 0">
                                <div class="course-item" v-for="lesson in item.list" :key="lesson.id" @click="triggerView(lesson)">
                                    <div class="course-banner">
                                        <img :src="lesson.coverUrl">
                                    </div>
                                    <div class="course-title">
                                        <div class="course-type">{{lesson.category | formatCategory}}</div>
                                        <b>{{lesson.name}} {{lesson.partName}}</b>
                                    </div>
                                </div>
                            </template>
                            <div class="text-center" v-else>
                                今日无课程
                            </div>
                        </div>
                    </mt-tab-container-item>
                </mt-tab-container>
            </div>
        </div>

        <div class="footer">
            时光企鹅 提供技术支持
        </div>
        <mt-datetime-picker ref="datePicker" :type="pickerConf.type" :startDate="pickerConf.startDate" :endDate="pickerConf.endDate" v-model="pickerValue" @confirm="pickerConfirm"> </mt-datetime-picker>
        <div v-show="showShareTip" class="v-modal" style="z-index: 2000;" @click="showShareTip = false"></div>
        <div v-show="showShareTip" class="share-tip-dialog">
            <div class="tip-container">
                <div class="back">
                    <div class="talk">
                        你还没有完成分享任务哦~ <br>完成任务后再来学习吧！
                    </div>
                </div>
                <div class="msg">任务进度：还需要{{needShareCount}}次转发分享~</div>
                <div class="btn-wrap"><mt-button @click="goShare">立即前往分享</mt-button></div>
            </div>
        </div>
    </div>
</template>

<script>
    const wx = require('weixin-js-sdk');
    import { TabContainer, TabContainerItem, DatetimePicker } from 'mint-ui';
    import { getTimestamp, getStudents, getCourseConf, getLesson, getCourseConfByVisitor, getStudentsByVisitor, getLessonByVisitor, shareGoalAchieved, getSDKConfig } from '@/api'
    export default {
        name: 'course-preview',
        components: {
            'mt-tab-container': TabContainer,
            'mt-tab-container-item': TabContainerItem,
            'mt-datetime-picker': DatetimePicker
        },
        props: {
            manager: {
                type: Boolean,
                default: false
            },
            self: {
                type: String,
                default: ''
            },
            holderId: String
        },
        data() {
            const year = new Date().getFullYear()
            return {
                showShareTip: false,
                lessonTime: '',
                customerId: '',
                needShareCount: 0,
                pickerConf: {
                    startDate: new Date(year - 1 + '-01-01'),
                    endDate: new Date(year + 1 + '-12-31'),
                    type: 'date'
                },
                courseInfo: {
                    name: '课程列表',
                    introduction: '企鹅时光课程',
                },
                pickerValue: new Date(),
                active: '',
                nowDate : '',
                totalStudentsCount: 3,
                schoolmate: [],

                lessonList: []
            }
        },
        filters: {
            formatCategory: function(v) {
                let catName = ''
                switch (v + '') {
                    case '1':
                        catName = '英语';
                        break;
                    case '2':
                        catName = '健康';
                        break;
                    case '3':
                        catName = '中文';
                        break;
                    case '4':
                        catName = 'STEM';
                        break;
                    case '5':
                        catName = '音乐';
                        break;
                    case '6':
                        catName = '艺术';
                        break;
                    case '7':
                        catName = '数学';
                        break;
                    case '8':
                        catName = '育儿';
                        break;
                }
                return catName;
            }
        },
        created() {
            this.initShareSDK()
            this.getBaseInfo()
            getTimestamp().then( res=>{
                this.nowDate = res.data.result
                this.getCourseList(this.nowDate)
            })
        },
        methods: {
            timeFormat(dt) {
                let time = dt ? new Date(dt) : new Date(this.nowDate)
                let day = ''
                switch (time.getDay()) {
                    case 0:
                        day = '日';
                        break;
                    case 1:
                        day = '一';
                        break;
                    case 2:
                        day = '二';
                        break;
                    case 3:
                        day = '三';
                        break;
                    case 4:
                        day = '四';
                        break;
                    case 5:
                        day = '五';
                        break;
                    case 6:
                        day = '六';
                        break;

                }
                return {
                    day,
                    date: time.getDate().toString().padStart(2, '0'),
                    fullDate: time.getFullYear() + '-' + (time.getMonth() + 1).toString().padStart(2, '0') + '-' + time.getDate().toString().padStart(2, '0')
                }
            },

            initShareSDK(){
                let url = window.location.href.split('#')[0]
                getSDKConfig({ url }).then( res => {
                    let cf = res.data.result
                    // alert('appId:'+cf.appId+'\n'+'timestamp:'+cf.timestamp+'\n'+'nonceStr:'+cf.nonceStr+'\n'+'signature:'+cf.signature)
                    wx.config({
                        // debug: true, // 开启调试模式
                        appId: cf.appId, // 必填，公众号的唯一标识
                        timestamp: cf.timestamp, // 必填，生成签名的时间戳
                        nonceStr: cf.nonceStr, // 必填，生成签名的随机串
                        signature: cf.signature,// 必填，签名
                        jsApiList: ['onMenuShareAppMessage', 'onMenuShareTimeline', 'hideMenuItems'] // 必填，需要使用的JS接口列表
                    });
                })
                
                wx.ready(function(){
                    wx.hideMenuItems({
                        menuList: ['menuItem:share:qq', 'menuItem:share:weiboApp', 'menuItem:share:QZone'] // 要隐藏的菜单项，只能隐藏“传播类”和“保护类”按钮
                    });
                });
            },
            initShare(){
                let _t = this
                wx.ready(function(){
                    let shareConf = {
                        title: _t.courseInfo.name, // 分享标题
                        link:  _t.self ? ('http://wx.17zhangda.tv/wxbk/customerlogin/verify?holderId='+_t.holderId) : window.location.href,
                        imgUrl: 'http://penguin-courses.oss-cn-shanghai.aliyuncs.com/image/qie2.png?x-oss-process=style/square', // 分享图标
                        success: function () {
                            // window.alert('分享成功')
                        }
                    }
                    console.log(shareConf.link)
                    wx.onMenuShareAppMessage(Object.assign({}, shareConf, {desc: _t.courseInfo.introduction}))
                    wx.onMenuShareTimeline(shareConf)
                });
            },
            getBaseInfo() {
                if (this.manager || this.self) {
                    getStudents({ limit: 8, offset: 0 }).then(res => {
                        this.totalStudentsCount = res.data.result && res.data.result.totalCount ? res.data.result.totalCount : 0
                        let list = []
                        res.data.result && res.data.result.detail.forEach(e => {
                            list.length < 8 && e.status==1 && list.push(e.customerHeadImageUrl)
                        })
                        this.schoolmate = list
                    })
                    getCourseConf().then(res => {
                        const { name, introduction } = res.data.result
                        this.courseInfo.name = name
                        this.courseInfo.introduction = introduction
                        this.initShare()
                    })
                } else {
                    getStudentsByVisitor({ limit: 8, offset: 0, holderId: this.holderId }).then(res => {
                        this.totalStudentsCount = res.data.result && res.data.result.totalCount ? res.data.result.totalCount : 0
                        let list = []
                        res.data.result && res.data.result.detail.forEach(e => {
                            list.length < 8 && e.status==1 && list.push(e.customerHeadImageUrl)
                        })
                        this.schoolmate = list
                    })
                    getCourseConfByVisitor({holderId: this.holderId}).then(res => {
                        const { name, introduction } = res.data.result
                        this.courseInfo.name = name
                        this.courseInfo.introduction = introduction
                        this.initShare()
                    })
                    
                }
            },
            
            getCourseList(cur){
                let pms = this.getDateRange(cur),
                    queryUrl = (this.manager||this.self) ? getLesson : getLessonByVisitor
                if(!this.manager && !this.self){
                    pms.holderId=this.holderId
                }
                queryUrl(pms).then(res => {
                    let list = this.getDateList(this.timeFormat(cur).fullDate),
                        obj = {},
                        src = res.data.result
                    for (let e of Object.keys(src)) {
                        let date = this.timeFormat(e).date
                        obj[date] = src[e]
                    }
                    list.forEach(e => {
                        e.list = obj[e.date] || []
                    })
                    this.lessonList = list
                    this.$nextTick(function(){
                        this.active = 'tab-container-' + new Date(cur).getDate().toString().padStart(2,'0')
                    })
                })
            },
            triggerView(lesson){
                if(this.self){
                    return false
                } else if (this.manager) {
                    if(lesson.game){
                        window.location.href = lesson.gameUrl
                        // this.$router.push('/game?url=' + encodeURIComponent(lesson.gameUrl))
                    } else {
                        this.$router.push('/detail/'+lesson.id)
                    }
                } else{
                    this.lessonTime = new Date(lesson.startTime).getTime().toString().substring(0,10)
                    shareGoalAchieved({holderId: this.holderId, timestamp: this.lessonTime}).then( res => {
                        let result = res.data.result
                        if(result.achieved !== 1){
                            this.needShareCount = result.need - result.current
                            this.showShareTip = true
                            this.customerId = result.customerId
                        } else {
                            if(lesson.game){
                                window.location.href = lesson.gameUrl
                            } else {
                                this.$router.push('/detail/'+lesson.id+(this.manager ? '' : '?hId='+this.holderId))
                            }
                            
                        }
                    })
                }
            },
            goShare(){
                this.$router.push('/share?hId='+this.holderId + '&pId='+this.customerId + '&time=' + this.lessonTime)
            },
            getDateRange(cur){
                let time = new Date(cur).getTime()
                let start = this.timeFormat(time - 24 * 3600 * 1000 * 3).fullDate
                let end = this.timeFormat(time + 24 * 3600 * 1000 * 4).fullDate
                return {
                    startTimeStart: start,
                    startTimeEnd: end,
                }
            },
            getDateList(cur) {
                let list = [],
                    time = new Date(cur).getTime()
                let nd = new Date(this.nowDate).getTime()
                for (let i = 1; i < 8; i++) {
                    let d = time - 24 * 3600 * 1000 * (4 - i)
                    let cd = new Date(d).getTime()
                    let t = this.timeFormat(d)
                    list.push({
                        date: t.date,
                        day: t.day,
                        before: cd <= nd ? true : false,
                        list: []
                    })
                }
                return list
            },
            openPicker() {
                this.$refs.datePicker.open();
            },
            pickerConfirm(v) {
                // let date = v.getFullYear() + '-' + (v.getMonth() + 1) + '-' + v.getDate()
                this.getCourseList(v)
                // console.log(date)
            }
        },
    }
</script>

<style scoped lang="scss">
    .course {
        position: absolute;
        top: 0;
        bottom: 0;
        left: 0;
        right: 0;
        background-color: var(--deepBack);
        .banner {
            height: 1.3rem;
            background-image: url('./img/banner-back.png');
            background-size: cover;
            background-repeat: no-repeat;
            box-sizing: border-box;
            padding: .55rem .1rem 0;
            text-align: center;
            color: #fff;

            .course-name {
                font-size: 22px;
                padding-bottom: .06rem;
            }
        }

        .schoolmate {
            line-height: .4rem;
            background: #fff;
            padding: .1rem .15rem;

            .count {
                color: var(--primaryColor);
                font-size: 18px;
                font-weight: bold;
                position: relative;
                bottom: 0;
            }

            .list {
                position: relative;
                height: .4rem;

                img {
                    width: .28rem;
                    height: .28rem;
                    position: absolute;
                    top: .06rem;
                    border: solid 1px #fff;
                    border-radius: 50%;
                }
            }

            .more {
                color: var(--tipColor);
                font-size: 18px;
                padding-left: 5px;
            }
        }

        .course-nav {
            margin-top: .1rem;
            background: #fff;
            text-align: right;
            color: var(--notActiveText);

            .mt-col-1,.mt-col-2 {
                position: relative;
                height: .8rem;
                padding-top: .1rem;

                &.active {
                    .date {
                        border-color: var(--primaryColor);
                        background-color: var(--primaryColor);
                        color: #fff;
                    }
                }
            }

            .picker-col {
                text-align: center;
                max-width: 12.5%;
                img {
                    width: 70%;
                    position: absolute;
                    bottom: .2rem;
                    left: .05rem;
                }
            }

            .day {
                padding-right: .1rem;
                line-height: 2.2;
            }

            .line {
                position: absolute;
                z-index: 0;
                bottom: .28rem;
                height: .06rem;
                width: 100%;
                background-color: var(--notActiveBorder);
                &.primary{
                    background-color: var(--primaryColor);
                }
            }

            .date {
                text-align: center;
                line-height: .22rem;
                width: .22rem;
                height: .22rem;
                font-size: 13px;
                border: solid .03rem var(--notActiveBorder);
                border-radius: 50%;
                background: #fff;
                color: var(--primaryColor);
                position: absolute;
                z-index: 1;
                bottom: .175rem;
                right: 0;
                &.primary{
                    border-color: var(--primaryColor);
                }
            }
        }
        .page-tab-container{
            min-height: 250px;
        }
        .course-item-wrap {
            padding: .2rem;
            // margin-bottom: .2rem;
            background: #fff;
            min-height: 260px;
        }

        .course-item {
            border-radius: .2rem;
            box-shadow: #f2f2f2 0 0 2px 2px;
            margin-bottom: .2rem;
            &:last-child{
                margin-bottom: 0;
            }
            .course-banner {
                height: 1.8rem;
                border-radius: .2rem .2rem 0 0;

                img {
                    border-radius: .2rem .2rem 0 0;
                    width: 100%;
                    height: 1.8rem;
                }
            }

            .course-title {
                line-height: .24rem;
                padding: .12rem;
                font-size: 15px;
                white-space: nowrap;
                overflow: hidden;
                .course-type {
                    line-height: .18rem;
                    padding: 0 4px;
                    font-size: 12px;
                    margin-right: .05rem;
                    margin-top: .02rem;
                    float: left;
                    border: solid 1px var(--primaryColor);
                    color: var(--primaryColor);
                    border-radius: 4px;
                }
                .part{
                    font-size: 13px
                }
            }
        }
        .footer{
            padding: 10px 0;
            text-align: center;
            font-size: 12px;
            color: #ccc;
            background-color: var(--deepBack);
        }
    }
    .share-tip-dialog /deep/ {
        .btn-wrap{
            text-align: center;
            padding: .06rem 0;
        }
        .mint-button--default{
            border-radius: 24px;
            padding: 0 .3rem;
            background-color: #fff;
            color: var(--primaryColor);

        }
    }
</style>